package net
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	
	 [event(name="analyseMsg",type="net.MessageEvent")] 
	public   class  AbstractFetionUser extends EventDispatcher
	{
	
//	public var SERVER_ADDRESS:String="218.202.228.223:9080";
//	public var SERVER_IP:String="218.202.228.223";
//	public var SERVER_PORT:String="9080";

//	public var SERVER_ADDRESS:String="218.202.228.219:9080";
//	public var SERVER_IP:String="218.202.228.219";
//	public var SERVER_PORT:String="9080";
//	public var TOMCAT_PORT:String="8080";

	public var SERVER_IP:String="218.202.228.225";
	public var SERVER_PORT:String="7601";
	public var SERVER_ADDRESS:String=SERVER_IP+":"+SERVER_PORT;	
	public var TOMCAT_PORT:String="7602";
	
//	public var SERVER_ADDRESS:String="localhost:7601";
//	public var SERVER_IP:String="localhost";
//	public var SERVER_PORT:String="7601";
//	public var TOMCAT_PORT:String="8080";

	public var item:String="";
	public var LOGIN_FLAG:int = 1;		
		
	public  var I_NONCE:int = 10;	
	public  var I_SENDMSG:int = 11;
	public  var I_RECMSG:int = 12;
	public  var I_ADDUSER:int = 13;
	public  var I_DELUSER:int = 14;
	public  var I_MODIFYUSER:int = 15;
	public  var I_MODIFYSTAUTS:int = 16;
	public  var I_MODIGYNICKNAME:int = 17;
	public  var I_USERRIGHT:int = 18;
	public  var I_SHOWCONTANTLIST:int = 19;
	public  var I_SUBSTATUS:int = 20;
	public  var I_VIEWUSERINFO:int =21;	
	public  var I_MODIFYPWD:int =22;
	public  var I_KEEPALIVE:int =23;
	public  var I_RECFRIENDREQUEST:int =24;
	public  var I_PICCODE:int =25;
	public  var I_USERQUIT:int =26;
	public  var I_REGUSER:int =27;
	public  var I_FORGOTPWD:int =28;		
	public  var I_MODIFYUSERRIGHT:int =29;
	public  var I_SUB:int =26;
	public  var I_GETCONS:int =36;
	public  var I_LOGIN:int =30;
	public  var I_LOGIN_OK:int =31;	
	public  var I_LOGIN_FAIL:int =32;
	
	public  var seqKeep:int=3;
	public  var seqRQ:int=3;
	public  var seq:int=1;
	public  var urlId:int=1;
	public  var addSeq:int=1;
	public  var seqI:int=5;


	public var RETURN:String= "\r\n";
	public var DOMAIN:String = "fetion.com.cn";
	
	public var socket:Socket = null;
	public var mobile:String;
	public var password:String;
	public var fetionId:String;
	public var fetionUri:String;
	public var sex:int=1;
	public var status:String="1";
	public var nickname:String;	
	public var sipc_proxy:String;
	public var province:String;
	public var birthday:String;
	public var nonce:String;
	public var userRight:int;	
	public var newPassword:String;
	public var picId:String;
	public var picContent:String;
	public var picCode:String;
	public var smsCode:String;
	public var tmpMobile:String;
	public var tmpFetionId:String;
	public var tmpPwd:String;
	public var tmpIdnum:String;
	public var right:String;
	
	public function AbstractFetionUser()
	{	

	}
	
	public function check():void{
		var u:FetionUser=new FetionUser();
	}
	
	public function getUrlId():int{
		return urlId++;
	}
	
	private function randRange(min:Number, max:Number):Number {
    	var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
    	return randomNum;
	} 
	
	public function getAddQ():int{
		return addSeq++;
	}
	public function getI():int{
		return seqI++;
	}
	
	public function getQ():int{
		return seq++;
	}
	
	public function getRQ():int{
		return seqRQ++;
	}
	
	public function getSeqKeep():int{
		return seqKeep++;
	}

	public function connect():void{
  	 
      socket = new Socket( );
      socket.addEventListener( Event.CONNECT, onConnect);
	  socket.addEventListener( ProgressEvent.SOCKET_DATA, onRecSocketData );
      socket.addEventListener(Event.CLOSE,onClose);
      socket.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
	  socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurityError);
      socket.connect(getProxyIp(sipc_proxy),
					getProxyPort(sipc_proxy));
  	  
    }
    
    public function getProxyIp(proxy:String):String {
		return proxy.substring(0, proxy.indexOf(":"));
	}

	public function getProxyPort(proxy:String):int {
		return int(proxy.substring(proxy.indexOf(":") + 1));
	}

	public function getFetionId(fetionUri:String):String {
		var p1:int = fetionUri.indexOf(":");
		var p2:int = fetionUri.indexOf("@");
		return fetionUri.substring(p1 + 1, p2);
	}

	public function getIValue(src:String):int {
		var flag:String = "I:";
		var p1:int = src.indexOf(flag)+flag.length;
		var p2:int = p1+2;
		//var p2:int = src.lastIndexOf("Q:");
		var rst:String = src.substring(p1,p2);
		trace("I-->"+rst);
		return int(rst);
	}
	
    public function send(msg:String):void
	{
		if(socket==null){
			connect();
		}
		var message:ByteArray=new ByteArray();
		message.writeUTFBytes(msg+"&@OVER\n"); 
		socket.writeBytes(message);
		socket.flush();
		trace("Send==>**************************************Start**************************************");        	
        trace(msg);
        trace("Send==>***************************************End****************************************");

	}
	
	public function findNonce(src:String):String {
		var flag:String = "nonce=\"";
		var p1:int = src.indexOf(flag);
		var p2:int = src.lastIndexOf("\"");
		var rst:String = src.substring(p1+flag.length,p2);
		trace("Nonce-->"+rst);
		return rst;
	}
	
	public function findUri(src:String):String {
		var results:XML =new XML(src);
		var rst:String=results.child("user").attribute("uri");
		trace("Uri-->"+rst);
		return rst;
	}
	
	public function isLogin(src:String):Boolean {
		var flag:String = "SIP-C/2.0 200 OK";
		if(src.indexOf(flag)!=-1){
			return true;
		}else{
			return false;
		}
	}

	public function onRecSocketData(event:ProgressEvent):void
	{
		trace( "Socket received " + socket.bytesAvailable + " byte(s) of data:" );
	    while (socket.bytesAvailable ) {
        	//var data:String = socket.readUTF();
        	var data:String = socket.readUTFBytes(socket.bytesAvailable);
        	//r.readMultiByte(socket.bytesAvailable,"utf8");
            //Alert.show(data);
        	var iValue:int =getIValue(data);
			switch(iValue)
			{
			case I_LOGIN_OK:
				trace("Logon OK");
				var infos:Array = data.split("#");
				fetionId=infos[1].toString();
				fetionUri=infos[3].toString();
				mobile=infos[4].toString();
				break;
			case I_LOGIN_FAIL:
				trace("Logon Failed");				
				break;
			default:
				trace("Out of range");
				break;
           }
           
           
            var e:MessageEvent = new MessageEvent(data);
     	    this.dispatchEvent(e);
	    }	     

	}
    
    public function close():void{
     	socket.close();
    }
  
    public function onIOError(event:IOErrorEvent ):void {
//     	 var e:MessageEvent = new MessageEvent("IOErrorEvent=>"+event.text);
//     	 this.dispatchEvent(e);
//     	 Alert.show("请确认是否连接服务器！","提示");
     	 trace("IOErrorEvent..." );
    }
    public function onSecurityError( event:SecurityErrorEvent ):void {
//       	 var e:MessageEvent = new MessageEvent("安全访问错误=>"+event.text);
//     	 this.dispatchEvent(e);
       	 trace("安全访问错误...");
    }
  
    public function onClose( event:Event ):void {
//    	 var e:MessageEvent = new MessageEvent("连接已关闭=>"+event.target);
//     	 this.dispatchEvent(e);
//     	 Alert.show("请确认是否连接服务器！","提示");
     	 LOGIN_FLAG=3;
     	 //Alert.show("close");
     	 trace( "连接已关闭..." );
    }
    
    public function onConnect( event:Event ):void {
//    	var e:MessageEvent = new MessageEvent("连接已建立=>"+event.target);
//     	this.dispatchEvent(e);
     	trace( "连接已建立..." );

     	var data:String ="<FetionUser>" 
				+ "#M:" + mobile				
				+ "#F:"+fetionId 				
				+ "#P:"+password;
		send(data);
	 } 
	}
}